//创建一个router并暴露出去
import {createRouter, createWebHistory} from 'vue-router'
// import Register from '../views/Register.vue'
import Login from '@/views/Login.vue'
import Index from '@/views/Index.vue'
// import Student from '../views/other/Student.vue'
import pinia from '@/pinia'
import { useTokenStore } from '@/stores/userTokenStore'
//一个 router 管理多个route
const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/',
            redirect:'/login'
        },
        {
            path: '/index',
            component: Index,   // 默认路由
            meta: { requiresAuth: true }
        },
        {
            path: '/login',
            component: Login   // 默认路由
        },
    ]
})
// 全局路由守卫
router.beforeEach((to, from, next) => {
    let useToken = useTokenStore(pinia);
    if (to.meta.requiresAuth && !useToken) {
        // 需要登录但没 token，跳转到登录
        next("/login")
    } else {
        next()
    }
})

//暴露出去
export default router